package study.zhangbo.lock.distributed.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Created by zhangbo on 2020/10/28.
 */
@Component
public class RedisLockUtils {

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 根据key获取值
     * @param key
     * @return
     */
    public String getValue(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 校验key是否存在
     * @param key
     * @return
     */
    public boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }


    /**
     * 设置值
     * @param key
     * @param value
     */
    public void setValue(String key,String value) {
        redisTemplate.opsForValue().set(key,value,30, TimeUnit.SECONDS);
    }


    /**
     * 为key续期
     * @param key
     * @param time
     * @param timeUnit
     */
    public void addKeyTime(String key,int time,TimeUnit timeUnit) {
        redisTemplate.expire(key,time,timeUnit);
    }


    /**
     * 如果key不存在，则为key赋值值
     * @param key
     * @param value
     * @return
     */
    public boolean setNx(String key,String value) {
        return redisTemplate.opsForValue().setIfAbsent(key,value,30,TimeUnit.SECONDS);
    }


    /**
     * 删除key
     * @param key
     * @return
     */
    public boolean delKey(String key) {
        return redisTemplate.delete(key);
    }


}
